import gradio as gr
from pathlib import Path
import logging
from utils import (
    setup_logging, 
    load_model, 
    segment_sentence, 
    format_tagged_sentence
)

class HMMInterface:
    def __init__(self):
        self.logger = setup_logging()
        self.model = self._load_model()
        
    def _load_model(self):
        model_path = Path(r"D:\NLP-program\基于HMM的三位一体字标注汉语词法分析\flagged\hmm_model_best.pkl")
        model = load_model(str(model_path), self.logger)
        if model is None:
            raise RuntimeError("模型加载失败")
        return model
        
    def process_sentence(self, input_str: str) -> str:
        """处理输入句子"""
        try:
            # 预处理输入
            chars = list(input_str)
            if not chars:
                return "请输入文本"
                
            # 预测标签
            tags, _ = self.model.viterbi(chars)
            
            # 分词
            words = segment_sentence(chars, tags)
            
            # 格式化输出
            return format_tagged_sentence(words, tags)
            
        except Exception as e:
            self.logger.error(f"处理句子时发生错误: {str(e)}")
            return "处理失败: 请确保输入格式正确。每行应包含一个词和其对应的标签，格式为 '词 标签'，每个句子之间用空行分隔。"

def main():
    """启动Web界面"""
    interface = HMMInterface()
    
    demo = gr.Interface(
        fn=interface.process_sentence,
        inputs=gr.Textbox(lines=3, placeholder="请输入要分析的句子"),
        outputs="text",
        title="中文分词与词性标注系统",
        description="基于HMM的中文分词与词性标注"
    )
    
    demo.launch()

if __name__ == "__main__":
    main()